package com.learn.mq.config;

import com.learn.mq.listener.Listener2Msg;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import javax.annotation.PreDestroy;

/**
 * ClassName:RocketMQConfig
 * Package:com.learn.mq.config
 * Description:
 *
 * @Author:@郭先森
 * @Create:2025/7/30 - 7:31
 * @Version:v1.0
 */
@Configuration
public class RocketMQConfig {
    //sendMsg1
    private DefaultMQProducer learnClientProducer = new DefaultMQProducer("LearnClientProducer");;
    private DefaultMQPushConsumer learnClientConsumer = new DefaultMQPushConsumer("LearnClientConsumer");;

    private TransactionMQProducer transactionMQProducer = new TransactionMQProducer("TransactionMQProducer");
    private DefaultMQPushConsumer transactionMQConsumer = new DefaultMQPushConsumer("TransactionMQConsumer");
    @Bean
    public DefaultMQProducer learnClientProducer() throws MQClientException {
        learnClientProducer.setNamesrvAddr("115.190.104.193:9876");
        learnClientProducer.setRetryTimesWhenSendFailed(2);
        learnClientProducer.start();
        return learnClientProducer;
    }
    @Bean
    public DefaultMQPushConsumer defaultMQPushConsumer() throws MQClientException {
        learnClientConsumer.setNamesrvAddr("115.190.104.193:9876");
        return learnClientConsumer;
    }

    @Bean
    public TransactionMQProducer transactionMQProducer() throws Exception{
        transactionMQProducer.setNamesrvAddr("115.190.104.193:9876");
        transactionMQProducer.setTransactionListener(new Listener2Msg());
        transactionMQProducer.start();
        return transactionMQProducer;
    }
    @Bean
    public DefaultMQPushConsumer transactionMQConsumer(){
        transactionMQConsumer.setNamesrvAddr("115.190.104.193:9876");
        return transactionMQConsumer;
    }

    @PreDestroy
    public void shutdown() {
        // 应用关闭时自动调用
        if (learnClientConsumer != null) {
            learnClientConsumer.shutdown();
        }
        if (learnClientProducer != null) {
            learnClientProducer.shutdown();
        }
        if (transactionMQProducer != null) {
            transactionMQProducer.shutdown();
        }
        if (transactionMQConsumer != null) {
            transactionMQConsumer.shutdown();
        }
    }

}
